#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "life"
# Email: batistuta1977@163.com
# Date: 2017/7/11
import socket
ho_list = []  # 用于保存文件读取内容的机器名，列表类型
with open('hostna.txt','r') as f1:
    for i in f1.readlines():
        # print(i)
        ho_list.append(i.strip())
print(ho_list)

with open('host-ip.txt','w') as f2:
    for host in ho_list:
        print(host)
        try:
            ip = socket.getaddrinfo(host,None)[0][4][0] # 只保留IP部分
            # print(ip)
            f2.write(host+'->'+ip+'\n')
        except Exception as e:     # 有的无法正向解析的设备报错后，保证程序正常运行
            print('cannot lookup')
            f2.write(host + '->' + 'nofound' + '\n')
            continue
        #     f2.write(i + '->' + result[0][4][0])
        # print(result)

# print(result[0][4][0])
# import sys,socket
# result=socket.getaddrinfo('GLPAA01',None)
# print(result[0][4][0])